package cz.cuni.amis.episodic.bayes.utils.chart;

import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileOutputStream;

import org.jfree.chart.JFreeChart;

import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

/**
 * Outputs graphs to PDF file.
 * Inspired by http://viralpatel.net/blogs/generate-pie-chart-bar-graph-in-pdf-using-itext-jfreechart/
 * @author ik
 *
 */
public class PdfGraphDevice extends GraphPaintingDevice {


	public PdfGraphDevice(File rootDirectory) {
		super(rootDirectory);
	}
	public PdfGraphDevice(File rootDirectory, int width, int height) {
		super(rootDirectory, width, height);
	}

	
	@Override
	public void outputGraph(JFreeChart graph, File dir, String name)
			throws Exception {
		PdfWriter writer = null;

		Document document = new Document(new Rectangle(width, height));

		try {
			writer = PdfWriter.getInstance(document, new FileOutputStream(
					new File(dir, name+".pdf")));
			document.open();
			PdfContentByte contentByte = writer.getDirectContent();
			PdfTemplate template = contentByte.createTemplate(width, height);
			Graphics2D graphics2d = template.createGraphics(width, height,
					new DefaultFontMapper());
			Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width,
					height);

			graph.draw(graphics2d, rectangle2d);

			graphics2d.dispose();
			contentByte.addTemplate(template, 0, 0);

		} catch (Exception e) {
			e.printStackTrace();
		}
		document.close();
	}

}
